"""
认证异常模块
定义认证相关的自定义异常
"""

class SteHubAuthException(Exception):
    """SteHub认证异常基类"""
    
    def __init__(self, message: str, code: str = None, details: dict = None):
        self.message = message
        self.code = code or 'AUTH_ERROR'
        self.details = details or {}
        super().__init__(self.message)

class AuthenticationError(SteHubAuthException):
    """认证错误"""
    
    def __init__(self, message: str = "认证失败", details: dict = None):
        super().__init__(message, 'AUTHENTICATION_FAILED', details)

class AuthorizationError(SteHubAuthException):
    """授权错误"""
    
    def __init__(self, message: str = "授权失败", details: dict = None):
        super().__init__(message, 'AUTHORIZATION_FAILED', details)

class PermissionDeniedError(SteHubAuthException):
    """权限拒绝错误"""
    
    def __init__(self, message: str = "权限不足", details: dict = None):
        super().__init__(message, 'PERMISSION_DENIED', details)

class InvalidTokenError(SteHubAuthException):
    """无效令牌错误"""
    
    def __init__(self, message: str = "无效的令牌", details: dict = None):
        super().__init__(message, 'INVALID_TOKEN', details)

class TokenExpiredError(SteHubAuthException):
    """令牌过期错误"""
    
    def __init__(self, message: str = "令牌已过期", details: dict = None):
        super().__init__(message, 'TOKEN_EXPIRED', details)

class InvalidCredentialsError(SteHubAuthException):
    """无效凭据错误"""
    
    def __init__(self, message: str = "用户名或密码错误", details: dict = None):
        super().__init__(message, 'INVALID_CREDENTIALS', details)

class UserNotFoundError(SteHubAuthException):
    """用户未找到错误"""
    
    def __init__(self, message: str = "用户不存在", details: dict = None):
        super().__init__(message, 'USER_NOT_FOUND', details)

class UserInactiveError(SteHubAuthException):
    """用户未激活错误"""
    
    def __init__(self, message: str = "用户账户已被禁用", details: dict = None):
        super().__init__(message, 'USER_INACTIVE', details)

class AccountLockedError(SteHubAuthException):
    """账户锁定错误"""
    
    def __init__(self, message: str = "账户已被锁定", details: dict = None):
        super().__init__(message, 'ACCOUNT_LOCKED', details)

class TooManyAttemptsError(SteHubAuthException):
    """尝试次数过多错误"""
    
    def __init__(self, message: str = "尝试次数过多，请稍后重试", details: dict = None):
        super().__init__(message, 'TOO_MANY_ATTEMPTS', details)

class PasswordTooWeakError(SteHubAuthException):
    """密码太弱错误"""
    
    def __init__(self, message: str = "密码强度不足", details: dict = None):
        super().__init__(message, 'PASSWORD_TOO_WEAK', details)

class EmailAlreadyExistsError(SteHubAuthException):
    """邮箱已存在错误"""
    
    def __init__(self, message: str = "该邮箱已被注册", details: dict = None):
        super().__init__(message, 'EMAIL_ALREADY_EXISTS', details)

class UsernameAlreadyExistsError(SteHubAuthException):
    """用户名已存在错误"""
    
    def __init__(self, message: str = "该用户名已被使用", details: dict = None):
        super().__init__(message, 'USERNAME_ALREADY_EXISTS', details)

class VerificationCodeError(SteHubAuthException):
    """验证码错误"""
    
    def __init__(self, message: str = "验证码错误或已过期", details: dict = None):
        super().__init__(message, 'VERIFICATION_CODE_ERROR', details)

class TwoFactorRequiredError(SteHubAuthException):
    """需要双因素认证错误"""
    
    def __init__(self, message: str = "需要双因素认证", details: dict = None):
        super().__init__(message, 'TWO_FACTOR_REQUIRED', details)

class SocialAuthError(SteHubAuthException):
    """社交认证错误"""
    
    def __init__(self, message: str = "社交认证失败", details: dict = None):
        super().__init__(message, 'SOCIAL_AUTH_FAILED', details)

class OAuthError(SteHubAuthException):
    """OAuth错误"""
    
    def __init__(self, message: str = "OAuth认证失败", details: dict = None):
        super().__init__(message, 'OAUTH_ERROR', details)

class SessionExpiredError(SteHubAuthException):
    """会话过期错误"""
    
    def __init__(self, message: str = "会话已过期，请重新登录", details: dict = None):
        super().__init__(message, 'SESSION_EXPIRED', details)

class CSRFError(SteHubAuthException):
    """CSRF令牌错误"""
    
    def __init__(self, message: str = "CSRF令牌无效", details: dict = None):
        super().__init__(message, 'CSRF_ERROR', details)

class RateLimitExceededError(SteHubAuthException):
    """速率限制超出错误"""
    
    def __init__(self, message: str = "请求过于频繁，请稍后重试", details: dict = None):
        super().__init__(message, 'RATE_LIMIT_EXCEEDED', details)

def handle_auth_exception(error: SteHubAuthException):
    """
    处理认证异常的统一函数
    
    Args:
        error: 认证异常
        
    Returns:
        tuple: (响应字典, HTTP状态码)
    """
    from flask import jsonify
    
    response = {
        'error': error.code,
        'message': error.message,
        'success': False
    }
    
    if error.details:
        response['details'] = error.details
    
    # 根据异常类型确定状态码
    status_code = 400  # 默认状态码
    
    if isinstance(error, (AuthenticationError, InvalidCredentialsError, 
                         InvalidTokenError, TokenExpiredError, SessionExpiredError)):
        status_code = 401
    elif isinstance(error, (AuthorizationError, PermissionDeniedError)):
        status_code = 403
    elif isinstance(error, (UserNotFoundError,)):
        status_code = 404
    elif isinstance(error, (TooManyAttemptsError, RateLimitExceededError)):
        status_code = 429
    
    return jsonify(response), status_code